package com.htfyun.fragment.postil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.htfyun.CachePngToBmpManager;
import com.htfyun.Constants;
import com.htfyun.database.DaoSession;
import com.htfyun.database.GreenDaoManager;
import com.htfyun.database.PWNote;
import com.htfyun.database.PWNoteDao;
import com.htfyun.database.PngName;
import com.htfyun.database.PngNameDao;
import com.htfyun.fragment.base.BaseWithPageNumberAdapter;
import com.htfyun.utils.DebugLog;
import com.htfyun.utils.UsefulUtils;
import com.squareup.picasso.Picasso;

import org.geometerplus.zlibrary.ui.android.BuildConfig;
import org.geometerplus.zlibrary.ui.android.R;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by sst on 2017/12/28.
 */

public class HtfyunPWAdapter extends BaseWithPageNumberAdapter<PWNote, HtfyunPWAdapter.MyViewHolder>{

    private int screenWidth;
    private int screenHeight;
    public HtfyunPWAdapter(Activity context) {
        super(context);

        DisplayMetrics metric = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metric);
        screenWidth = metric.widthPixels;  // 屏幕宽度（像素）
        screenHeight = metric.heightPixels;  // 屏幕高度（像素）
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder holder = super.onCreateViewHolder(parent, viewType);
//        ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
//        lp.height = screenHeight / 5;
//        holder.itemView.setLayoutParams(lp);
        
        return holder;
    }

    @Override
    public void onBindViewHolder(HtfyunPWAdapter.MyViewHolder holder, int position) {

        super.onBindViewHolder(holder, position);
        
        DebugLog.e(" onBindViewHolder position = " + position);
        if (position == 0) {
            holder.imgPng.setImageResource(R.drawable.ic_add_circle_black_24dp);
            holder.txtName.setText(R.string.pw_add_page);
            
        } else {
            List<PWNote> items = getItems();
            if (items.size() <= position - 1) {
                return;
            }

            PWNote note = items.get(position - 1);

            DaoSession daoSession = GreenDaoManager.INSTANCE.getDaoSession();
            PngNameDao pngNameDao = daoSession.getPngNameDao();
            List<PngName> pngNames = pngNameDao.queryBuilder()
                    .where(PngNameDao.Properties.OtherUuid.eq(note.getUuid()))
                    .orderAsc(PngNameDao.Properties.Date)
                    .limit(1).list();
            if (pngNames.size() > 0) {
                PngName pngName = pngNames.get(0);
                String name = pngName.getPngName();

                String pngPath = Constants.toPngPath(name);

                DebugLog.e("width = " + screenWidth 
                        + ", height = " + screenHeight 
                        + ", holder.itemView.height = " + holder.itemView.getMeasuredHeight());

                Bitmap bmp = CachePngToBmpManager.INSTANCE.getBitmap(pngPath);

                DebugLog.e( "bmp = " + bmp + ", pngPath = " + pngPath);
                
                if (bmp == null) {

                    bmp = CachePngToBmpManager.INSTANCE.createBitmapByFilePath(pngPath, screenWidth / 5, screenHeight / 5);
                }

                if (bmp == null) {
                    holder.imgPng.setImageResource(R.drawable.default_error);
                } else {
                    holder.imgPng.setImageBitmap(bmp);
                }

//                Picasso.with(getContext().getApplicationContext())
//                        .load(new File(pngPath))
//                        .error(R.drawable.default_error)
//                        .resize(screenWidth / 5, screenHeight / 5)
//                        .tag(HtfyunPWFragment.PICASSO_TAG)
//                        .into(holder.imgPng);

                holder.txtName.setText(note.getName());
            }
        }

        final int pos = position;
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (pos == 0) {

                    DaoSession daoSession = GreenDaoManager.INSTANCE.getDaoSession();
                    PWNoteDao pwNoteDao = daoSession.getPWNoteDao();
                    PngNameDao pngNameDao = daoSession.getPngNameDao();

                    PWNote pwNote = new PWNote();
                    pwNote.setDate(new Date());
                    pwNote.setName(UsefulUtils.dateToString(pwNote.getDate()));
                    pwNote.setUuid(UUID.randomUUID().toString());
                    pwNote.setPngCount(1);


                    PngName pngName = new PngName();
                    pngName.setDate(pwNote.getDate());
                    pngName.setOtherUuid(pwNote.getUuid());
                    pngName.setUuid(UUID.randomUUID().toString());
                    pngName.setPngName(pngName.getUuid() + ".png");

                    pngNameDao.insert(pngName);
                    pwNote.setId(pwNoteDao.insert(pwNote));
                    
                    
                    onItemClick(pos, pwNote);
                } else {
                    if (getItems().size() > pos - 1 ) {
                        PWNote t = getItems().get(pos - 1);
                        onItemClick(pos - 1, t);
                    }
                }
               
            }
        });

//        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View view) {
//
//                return onItemLongClick(pos, null);
//            }
//        });
        
    }

    @Override
    public int getItemCount() {
        return super.getItemCount() + 1;
    }
    
    @Override
    public MyViewHolder getViewHolder(View view) {
        return new MyViewHolder(view);
    }

    @Override
    public int getLayoutId() {
        return R.layout.htfyun_pw_adapter_item;
    }

    
    @Override
    public void onItemClick(int position, PWNote pwNote) {

//        if (BuildConfig.USE_PHONE) {
//            return;
//        }

        String action = "com.htfyun.action.pw_work";
        if (BuildConfig.USE_PHONE) {
            action = "com.htfyun.action.pw_ui_test_work";
        }
        
        Intent intent = new Intent(action);
        
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("id", pwNote.getId().longValue());
        getContext().startActivity(intent);
        
    }

    @Override
    public boolean onItemLongClick(int position, PWNote pwNote) {
        DebugLog.e("11 onItemLongClick = " + position);

//        showListDialog();
        return true;
//        return super.onItemLongClick(position, pwNote);
    }

    private void showListDialog() {
        final String[] items = {"我是1", "我是2", "我是3", "我是4"};
        
        AlertDialog.Builder listDialog =
                new AlertDialog.Builder(getContext());
        listDialog.setTitle("我是一个列表Dialog");
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // which 下标从0开始
                // ...To-do
                Toast.makeText(getContext(),
                        "你点击了" + items[which],
                        Toast.LENGTH_SHORT).show();
            }
        });
        listDialog.show();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView imgPng;
        TextView txtName;

        public MyViewHolder(View itemView) {
            super(itemView);
            imgPng = (ImageView) itemView.findViewById(R.id.imgPng);
            txtName = (TextView) itemView.findViewById(R.id.txtName);

            imgPng.setEinkUpdateMode(View.EINK_DATA_MODE_A2, View.EINK_SHOW_MODE_A2);
            txtName.setEinkUpdateMode(View.EINK_DATA_MODE_A2, View.EINK_SHOW_MODE_A2);
        }
    }
}
